package flyshoes.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import flyshoes.mybatis.entity.ShippingInformation;
import flyshoes.mybatis.entity.UserBaseInfo;
import flyshoes.mybatis.entity.UserDetailInfo;
import flyshoes.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import flyshoes.mybatis.entity.Result;
import flyshoes.service.serviceImpl.UserServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserServiceImpl userServiceImpl;
    private final RedisTemplate redisTemplate;
    private GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(150, 40, 4);//设置验证码图片大小，40x30 图形，4 个字符

    private LineCaptcha lineCaptcha =CaptchaUtil.createLineCaptcha(150,40,4,4);
    @PostMapping("/login")
    /**登录*/
    public Result login(@RequestBody Map users) {

        return userServiceImpl.login(users);
    }

    @PostMapping("/register")
    /**注册*/
    public Result<UserBaseInfo> register(@RequestBody UserBaseInfo users) {
        return userServiceImpl.register(users);
    }

    @GetMapping("getCaptcha")
    /**获取验证码*/
    public Result<Map> getCaptcha() {
        //1.重新生成验证码
        lineCaptcha.createCode();
        //2.ByteArrayOutputStream：这是一个字节数组输出流，数据将被写入这个流中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //3.将生成的验证码图像写入到输出流中。
        lineCaptcha.write(outputStream);
        //4.设置图片编码为Base64，
        /*Base64.encode(outputStream.toByteArray())：将字节数组转换为 Base64 编码的字符串，以便在网页中以图像的形式显示。
        Base64 编码可以将二进制数据转换为 ASCII 字符串，使其更容易在 JSON 等格式中传输。
         */
        String imgData = Base64.encode(outputStream.toByteArray());
        //5.生成验证码标识并存储数据
        Map<String, Object> map = new HashMap<>();//创建map存储数据
        String captchaId = IdUtil.randomUUID();//生成验证码标识
        map.put("captchaId", captchaId);//存储验证码Id
        map.put("img", imgData);//存储图片数据
        //6.打印验证码并存储到 Redis
        String captchaKey = "captcha:" + captchaId;//redis中存储的key
        String captchaValue = lineCaptcha.getCode();//redis中存储的value
        redisTemplate.opsForValue().set(captchaKey, captchaValue, 12, TimeUnit.HOURS);
        System.out.println("验证码为：" + captchaValue);
        //7.返回结果
        return Result.success(map);
    }

    @PatchMapping("/updatePassword")
    /**更新密码*/
    public Result updatePassword(@RequestBody Map<String, String> params) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String checkPwd = params.get("check_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(checkPwd)) {
            return Result.fail(400,"缺少必要参数");
        }
        //校验旧密码
        if (userServiceImpl.checkOldPassword(oldPwd)) {
            //校验两次密码是否一致
            if (newPwd.equals(checkPwd)) {
                userServiceImpl.updatePassword(newPwd);
                return Result.success(null);
            } else {
                return Result.fail(400,"两次密码不一致");
            }
        } else {
            return Result.fail(400,"旧密码不正确");
        }
    }
    @GetMapping("/myAddress")
    /**查找用户地址*/
    public Result myAddress(){
        return userServiceImpl.myAddress();
    }

    @PostMapping("/newAddress")
    /**新增地址*/
    public Result<ShippingInformation> newAddress(@RequestBody ShippingInformation address) {
        return userServiceImpl.newAddress(address);
    }
    @PostMapping("/updateAddress")
    /**更新收货地址*/
    public Result updateAddress(@RequestBody ShippingInformation shippingInformation) {

        return userServiceImpl.updateAddress(shippingInformation);
    }
    @DeleteMapping("/{addressId}/deleteAddress") //删除地址
    public Result deleteAddress(@PathVariable Integer addressId){
        return userServiceImpl.deleteAddress(addressId);
    }


    @GetMapping("/queryMyInfo")
    /**查找用户详细信息*/
    public Result<UserDetailInfo> queryMyInfo() {
        return userServiceImpl.queryMyInfo();
    }

//    @PostMapping("/upload")
//    /**
//     * 暂不编写
//     * 更新用户头像*/
//    public Result<String> upload(MultipartFile file) throws IOException {
//        //把文件的内容存储到本地磁盘上
//        String originalFilename = file.getOriginalFilename();
//        //保证文件的名字是唯一的，从而防止文件覆盖
//        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//        file.transferTo(new File(""));
//        return Result.success("url访问地址...");
//    }

    @PutMapping("/updateMyInfo")
    /**更新用户信息*/
    public Result<UserDetailInfo> updateMyInfo(@RequestBody UserDetailInfo myInfo) {
        return userServiceImpl.updateMyInfo(myInfo);
    }

}
